//
//  XGOfflineDownloadViewController.swift
//  TodayNews
//
//  Created by monkey on 2020/2/10.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit

class XGOfflineDownloadViewController: UITableViewController
{
    // MARK: - 控制器生命周期方法
    
    override func viewDidLoad()
    {
        super.viewDidLoad()

        navigationItem.title = "离线下载"
        
        // 设置tableView
        setUpTableView()
        // 加载数据
        loadData()
    }
    
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
        
        viewModel.saveNewsCategories()
    }
    
    /// 视图模型
     private let viewModel: XGOfflineDownloadViewModel = XGOfflineDownloadViewModel()
}

// MARK: - 数据源和代理方法

extension XGOfflineDownloadViewController
{
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return viewModel.newsCategories?.count ?? 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.xg_dequeueReusableCell(indexPath: indexPath) as XGOfflineDownloadTableViewCell
        cell.newsCategoryModel = viewModel.newsCategories?[indexPath.row]
        return cell
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
    {
        tableView.deselectRow(at: indexPath, animated: false)
        
        viewModel.updateNewsCategoryModel(index: indexPath.row) {
            tableView.reloadRows(at: [indexPath], with: .fade)
        }
    }
}

// MARK: - 私有扩展

private extension XGOfflineDownloadViewController
{
    /// 设置tableView
    func setUpTableView() -> Void
    {
        tableView.rowHeight = 44
        tableView.xg_registerCell(cellType: XGOfflineDownloadTableViewCell.self)
        tableView.theme_backgroundColor = "colors.cell_background"
        tableView.theme_separatorColor = "colors.cell_separator"
    }
    
    /// 加载数据
    func loadData() -> Void
    {
        // 获取首页新闻分类数据
        viewModel.fetchNewsCategories { (isSuccess) in
            isSuccess ? self.tableView.reloadData() : ()
        }
    }
}
